<template>
	<div class="address">
		<van-address-list
		  :list="addressList"
			:switchable="false"
		  default-tag-text="默认"
		  @add="$router.push({ name: 'AddressSet' })"
		  @edit="(item) => $router.push({ name: 'AddressSet', query: {aid:item.aid} })"
			v-if="addressList.length"
		/>
		<van-empty description="未添加地址" v-else>
		  <van-button 
				round type="info" 
				class="bottom-button"
				@click="$router.push({ name: 'AddressSet' })" >
				添加地址
			</van-button>
		</van-empty>

	</div>
</template>

<script>
	import bus from '@/utils/eventBus.js'
	import { getAddress } from '@/api/order.js'
	export default {
		data() {
			return {
				addressList: []
			}
		},
		created() {
			this._getAddress()
			// 修改地址以及添加地址传递的通知
			bus.$on('refresh-address', () => {
				this._getAddress()
			})
		},
		methods: {
			// 获取地址列表
			_getAddress() {
				const tokenString = window.sessionStorage.getItem('token')
				if(!tokenString) return this.$router.push({ name: "Login" })
				// 加载中
				this.$toast.loading({
					message: '加载中...',
					forbidClick: true
				})
				// 发起请求
				getAddress({
					tokenString
				})
				.then(({data:res}) => {
					console.log('获取地址',res)
					if (res.code !== 20000) return this.$toast.fail('请求异常,请重新尝试!')
					this.$toast.clear()
					// 遍历数据 使isDefault放回布尔值 / 添加数据
					res.result.forEach(item => {
						item.isDefault = Boolean(item.isDefault)
						item.address = `${item.province}${item.city}${item.county}${item.addressDetail}`
					})
					this.addressList = res.result
				})
				.catch(err => {
					this.$toast.fail('请求失败,请重新尝试!')
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.address{
		/deep/ .van-address-list{
			padding: 0;
			.van-radio-group{
				.van-address-item{
					border-radius: 0;
					&:not(:last-child){
						border-bottom: 1px solid #e8e8e8;
					}
				}
			}
			.van-tag--danger{
				background-color: #3498db;
			}
			.van-address-list__bottom{
				background: transparent;
				bottom: 10px;
				.van-button--danger{
					background-color: #3498db;
					border-color: #3498db;
				}
			}
		}
		/deep/ .van-empty__bottom{
			width: 80%;
			margin-top: 38px;
			.bottom-button{
				width: 100%;
				display: block;
			}
		}
	}
</style>